//时间格式转换为时间戳
function js_strto_time(time) {
    var new_str = time.replace(/:/g, '-');
    new_str = new_str.replace(/ /g, '-');
    new_str = new_str.replace(/\//g, '-');
    var arr = new_str.split("-");
    var datum = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return strtotime = datum.getTime() / 1000;
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime)*1000);
    var year= timestr.getFullYear(); 
    var month= timestr.getMonth()+1; 
    var date= timestr.getDate(); 
    var hour= timestr.getHours(); 
    var minute= timestr.getMinutes(); 
    var second= timestr.getSeconds(); 
    var datetime = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second; 
    return datetime;
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime) * 1000);
    var datetime = timestr.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    if (datetime.indexOf("上午") != -1) {
        datetime = datetime.replace(/上午/g, "");
        datetime = datetime.split(":")[0] + ":" + datetime.split(":")[1];
        datetime = datetime + " AM"
    }
    if (datetime.indexOf("下午") != -1) {
        datetime = datetime.replace(/下午/g, "");
        datetime = datetime.split(":")[0] + ":" + datetime.split(":")[1];
        datetime = datetime + " PM"
    }
    return datetime;
}

//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}

var base64 = new Base64();
var type = getQueryString("type");
var DepotID = getQueryString("DepotID");
var DepotName = getQueryString("DepotName");
DepotName = base64.decode(DepotName);

var PolicyObj = {
    "MessageSerialNo": "11",
    "C_TimeSlots": {
        "C_TimeSlot": []
    }
}

function save() {
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }

    var comment = $(".policy_desc").val();
    PolicyObj.AppType = $(".AppType").val();
    PolicyObj.AppID = $(".AppID").val();
    PolicyObj.AppName = $(".AppName").val();
    PolicyObj.App_Threshold_Up_ABS = $(".Threshold_UP").val();
    PolicyObj.App_Threshold_Dn_ABS = $(".Threshold_DN").val();

    if (PolicyObj.AppID === "0" && PolicyObj.AppName === "") {
        alert("请输入应用名称！");
        return;
    }

    var policy = JSON.stringify(PolicyObj);

    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/create.do",
        data: {comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("添加成功！");
                previous();
            } else {
                alert("添加失败!")
            }
        }
    });
}

function edit() {
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    PolicyObj.AppType = $(".AppType").val();
    PolicyObj.AppID = $(".AppID").val();
    PolicyObj.AppName = $(".AppName").val();
    PolicyObj.App_Threshold_Up_ABS = $(".Threshold_UP").val();
    PolicyObj.App_Threshold_Dn_ABS = $(".Threshold_DN").val();

    if (PolicyObj.AppID === "0" && PolicyObj.AppName === "") {
        alert("请输入应用名称！");
        return;
    }

    var policy = JSON.stringify(PolicyObj);

    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/update.do",
        data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("修改成功！");
                previous();
            } else {
                alert("修改失败!")
            }
        }
    });
}

function showData(resp) {
    var messageType = resp.MessageType;
    var messageNo = resp.MessageNo;
    var instanceName = resp.Instance;
    var comment = resp.Comment;
    PolicyObj = resp.Content;

    $(".policy_desc").val(comment);
    $(".AppType").val(PolicyObj.AppType);
    $(".AppID").val(PolicyObj.AppID);
    $(".AppName").val(PolicyObj.AppName);
    $(".Threshold_UP").val(PolicyObj.App_Threshold_Up_ABS);
    $(".Threshold_DN").val(PolicyObj.App_Threshold_Dn_ABS);

    refreshTimeSeg();
}

function refreshTimeSeg() {
    var obj = $(".C_TimeSlots tbody");
    var cont = "";
    var number = 0;
    var webTypes = PolicyObj.C_TimeSlots.C_TimeSlot;
    for (var i in webTypes) {
        cont += "<tr>";
        cont += "<td>" + js_date_time(webTypes[i].C_Starttime * 1) + "</td>";
        cont += "<td>" + js_date_time(webTypes[i].C_Stoptime * 1) + "</td>";
        cont += "<td><a href='javascript:delTimeSeg(" + number + ")'>&nbsp;删&nbsp;除&nbsp;</a></td>";
        cont += "</tr>";
        number++;
    }
    obj.html("");
    obj.append(cont);
}

function delTimeSeg(num) {
    PolicyObj.C_TimeSlots.C_TimeSlot.splice(num, 1);
    refreshTimeSeg();
}

function closeBox() {
    $("#myModal").modal('hide')
//    $("#myModal").remove();
}

function addTimeSegBox() {
//    var cont = '';
//    cont += "<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>";
//    cont += "            <div class='modal-dialog'>";
//    cont += "                <div class='modal-content'>";
//    cont += "                    <div class='modal-header'>";
//    cont += "                        <button type='button' class='close' data-dismiss='modal'><span aria-hidden='true'>&times;</span></button>";
//    cont += "                        <h4 class='modal-title' id='myModalLabel'>添加时间段</h4>";
//    cont += "                    </div>";
//    cont += "                    <div class='modal-body'>";
//    cont += "                        <form class='form-horizontal'>";
//    cont += "                            <div class=' row-fluid'>";
//    cont += "                                <div class='control-group'>";
//    cont += "                                    <label class='control-label' for='CStartTime'>起始时间：</label>";
//    cont += "                                    <div class='controls'>";
//    cont += "                                        <input type='text' id='CStartTime' name='CStartTime' class='CStartTime ip' required/>";
//    cont += "                                    </div>";
//    cont += "                                </div>";
//    cont += "                                <div class='control-group'>";
//    cont += "                                    <label class='control-label' for='CEndTime'>结束时间：</label>";
//    cont += "                                    <div class='controls'>";
//    cont += "                                        <input type='text' id='CEndTime' name='CEndTime' class='CEndTime number' required/>";
//    cont += "                                    </div>";
//    cont += "                                </div>";
//    cont += "                            </div>";
//    cont += "                        </form>";
//    cont += "                    </div>";
//    cont += "                    <div class='modal-footer'>";
//    cont += "                        <a href='javascript:void(0)' class='btn btn-default' onclick='closeBox()'>取消</a>";
//    cont += "                        <a href='javascript:void(0)' class='btn btn-primary' onclick='addTimeSegment()'>确定</a>";
//    cont += "                    </div>";
//    cont += "                </div>";
//    cont += "            </div>";
//    cont += "        </div>";
//    $("body").append(cont);
//    var time = new Date().getTime();
//    time = Math.floor(time / 1000);
//    $('#CStartTime').val(js_date_time(time));
//    $('#CEndTime').val(js_date_time(time));
    $("#myModal").modal({
        show: true
    });
//    $("#myModal").focus();
//    $("#myModal").blur();

}

function addTimeSegment() {
    var startTime = js_strto_time($("#CStartTime").val());
//    startTime = js_strto_time(startTime) + "";
    var endTime = js_strto_time($("#CEndTime").val());
//    endTime = js_strto_time(endTime) + "";
    PolicyObj.C_TimeSlots.C_TimeSlot.push({
        "C_Starttime": startTime,
        "C_Stoptime": endTime
    })
    refreshTimeSeg();
    closeBox();
}
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");
    
    showData(souData);
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}